package com.zhiqian.service;

import com.zhiqian.bean.RpcRequest;
import com.zhiqian.bean.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy implements InvocationHandler {
//    private String host;
//    private int port;
//    public RpcClientProxy(String host,int port){
//        this.host=host;
//        this.port=port;
//    }
    private RpcClient rpcClient;
    public RpcClientProxy(RpcClient rpcClient){
        this.rpcClient=rpcClient;
    }

    @SuppressWarnings("unchecked")
    public <T>T getProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest= RpcRequest.builder()
                .interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameters(args)
                .paramTypes(method.getParameterTypes())
                .build();
        return ((RpcResponse)rpcClient.sendRequest(rpcRequest)).getData();
    }
}
